#include "Particles.h"
#include "Utils.h"

#include <eastl/algorithm.h>
#include <eastl/vector.h>

eastl::vector<Part> Particles;
Fnt ParticleFont = 0;

void InitParticleSystem()
{
	Particles.reserve(1024);
}

Part* AddParticle( const Vec& position, const Part* definition /*= 0*/ )
{
	Particles.resize(Particles.size()+1);
	Part& p = Particles.back();
	if (definition)
		p = *definition;
	p.Pos = position;
	return &p;
}

bool IsDead(const Part& p) { return p.Life <= 0; }

void DoParticles(float dt)
{
	for (size_t i=0; i<Particles.size(); i++)
	{
		Part& p = Particles[i];
		p.Age(dt);
	}
	if (!Particles.empty())
		Particles.erase(eastl::remove_if(Particles.begin(), Particles.end(), &IsDead), Particles.end());
}

void DrawParticles(const Vec& offset)
{
	for (size_t i=0; i<Particles.size(); i++)
	{
		Part& p = Particles[i];
		if (p.Life != 0)
		{
			Vec pos = p.Pos + offset;
			switch (p.Type)
			{
			case PT_Img:
				DrawPic(p.Img, pos.X, pos.Y, p.Angle, p.Col);
				break;
			case PT_Text:
				DrawFilledRoundRect(pos.X-16, pos.Y+FntHeight(ParticleFont)/2-16, 32, 32, 4, 4, Color::Black(0.5f));
				DrawFntCenter(ParticleFont, pos.X, pos.Y, p.Col, p.Text, p.Data);
				break;
			}
		}
	}
}

Part* ShootParticle( const Vec& position, const Vec& velocity, const Part* definition /*= 0*/ )
{
	Part* p = AddParticle(position, definition);
	p->Speed = velocity;
	return p;
}